package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/*
 * 接受文本消息
 * */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {


    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> map) {
        log.info("接受微信文本消息......");
        String content = map.get("Content");
        if (!KEY_WORD.equals(content)) {
            return "";
        }
        String toUserName = map.get("ToUserName");
        String fromUserName = map.get("FromUserName");
        long createTime = System.currentTimeMillis() / 1000; // 微信要求的时间戳单位是秒

        int num = new Random().nextInt(1000);
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
        redisUtil.setNx(numKey, fromUserName, 5L, TimeUnit.MINUTES);

        String numContent = "您当前的验证码是：" + num + "!  5分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>" + createTime + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        System.out.println(replyContent);
        return replyContent;
    }
}
